import datetime
import mongoengine as db
from app.db import BaseDocument


class Audit(BaseDocument):
    """
     "_id": {
          "$oid": "60a74884058ddc001b77ca98"
     },
     "type": "ops",
     "logSource": "front",
     "level": "info",
     "affects": [
          "22222222.163.com"
     ],
     "message": "[22222222.163.com]创建监测任务",
     "uid": "6087d1bcc1bec6001b985eea",
     "username": "admin@knownsec.com",
     "ip": "10.8.25.74",
     "module": "job",
     "actionType": "create",
     "actionMessage": "新增资产",
     "detail": "新增资产，资产名称：aAAAAAA，资产地址：https://22222222.163.com。",
     "createTime": {
          "$date": "2021-05-21T05:43:32.243Z"
     },

    Args:
        BaseDocument ([type]): [description]
    """
    type = db.StringField(choices=['ops', 'auth'],
                          default='ops', required=True)
    logSource = db.StringField(
        choices=['front', 'back'], default='front', required=True)
    level = db.StringField(
        choices=['info', 'error'], default='info', required=True)
    affects = db.ListField(db.StringField())
    message = db.StringField()
    uid = db.StringField()
    username = db.StringField()  #前台请求记录登录用户, OMS发送的请求 ?_username=oms@xxx.com
    ip = db.StringField()
    module = db.StringField()
    actionType = db.StringField(choices=['create', 'read', 'update', 'delete'],
                          default='read')
    actionMessage = db.StringField()
    detail = db.StringField()
    createTime = db.DateTimeField()

    meta = {
        'collection': 'audits',
        'strict': False
    }

    def save(self, *args, **kwargs):
        if not self.createTime:
            self.createTime = datetime.datetime.utcnow()
        return super(Audit, self).save(*args, **kwargs)
